import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.*;
import org.apache.commons.io.FileUtils;

public class FileOpera {
    public static Map<String,Object> JsonRead(String filename){                           //读取json
        String path="users/" +filename+"/"+filename+ ".json";
        Map<String, Object> map;
        String fileContent;
        try {
            fileContent = FileUtils.readFileToString(new File(path),"UTF-8");
        } catch (IOException e) {
            return null;   // 文件操作错误，返回null
        }
        map = JSONObject.parseObject(fileContent);
        return map;
    }
    public static void JsonWrite(String filename, Map<String,Object> account){     // 写入Json
        String path="users/"+filename+"/"+filename+ ".json";
        File file = new File(path);
        JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(account)); //将map转换为Json对象
        try {
            FileUtils.writeStringToFile(file,itemJSONObj.toJSONString(),"UTF-8",false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String> ReadLines(String type1,String type2, String filename){      // 文件按行读取，存储在List中
        String path=type1+"/"+type2+"/"+ filename +".txt";
        List<String> filecontent=null;
        try {
            filecontent=FileUtils.readLines(new File(path),"UTF-8");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return filecontent;
    }


    public static void writeAll(String ID, String type,List<String> content){         // 把List内容写入文件
        String path="users/" +ID+"/";
        if(type.equals("error"))
        {
            path+="Error_book.txt";
            File file = new File(path);
            try {
                FileUtils.writeLines(file,"UTF-8",content,true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static int getFileNums(String type1,String type2){                 // 获取目录下的文件数
        File file = new File(type1+"/"+type2);
        List<File> fileList = (List<File>)FileUtils.listFiles(file,null,false);
        return fileList.size();
    }




}
